package models

import (
	"time"

	"github.com/astaxie/beego/orm"
)

type Article struct {
	Id      int
	Title   string
	Content string
	Created time.Time
	Update  time.Time
}

func (u *Article) TableName() string {
	return "cms_article"
}

func init() {
	orm.RegisterModel(&Article{})
}

//获取文章列表
func GetArticleList() []Article {
	var article []Article
	o := orm.NewOrm()
	//查询所有用户所有内容
	_, _ = o.QueryTable("cms_article").All(&article)
	return article
}

//获取单个文章数据
func GetArticleById(id int) *Article {
	var article = Article{}
	o := orm.NewOrm()
	article.Id = id
	err := o.Read(&article)

	if err == orm.ErrNoRows {
		return nil
	} else if err == orm.ErrMissPK {
		return nil
	}

	return &article
}

//新增文章
func AddArticleData(title string, content string) int64 {
	o := orm.NewOrm()
	var article = Article{}
	var t = time.Now()
	article.Title = title
	article.Content = content
	article.Created = t
	article.Update = t
	id, _ := o.Insert(&article)
	return id
}

//更改文章数据
func UpdateArticle(title string, content string, id int) error {
	o := orm.NewOrm()
	var article = Article{}
	article.Id = id
	article.Title = title
	article.Content = content
	article.Update = time.Now()
	_, err := o.Raw("update cms_article set title = ?,content = ?,`update` = ? where id = ?", article.Title, article.Content, article.Update, article.Id).Exec()
	return err
}

//删除单个文章
func DelArticleById(id int) (int64, error) {
	o := orm.NewOrm()
	var article = Article{}
	article.Id = id
	num, err := o.Delete(&article)
	return num, err
}
